package utils

import (
	"crypto/cipher"
	"crypto/des"
	"crypto/hmac"
	"crypto/md5"
	"crypto/sha1"
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"io"
)

// Md5 计算 str 的md5 值
func Md5(str string) string {

	hs := md5.New()
	io.WriteString(hs, str)
	return fmt.Sprintf("%X", hs.Sum(nil))
}

func Sha256(str string) string {
	sh := sha256.New()
	sh.Write(UnsafeString2Byte(str))
	return fmt.Sprintf("%X", sh.Sum(nil))
}

func Sha1(str string) string {
	sh := sha1.New()
	sh.Write(UnsafeString2Byte(str))
	return fmt.Sprintf("%X", sh.Sum(nil))
}

func HmacMd5(data, key string) string {
	hmacHash := hmac.New(md5.New, []byte(key))
	hmacHash.Write([]byte(data))
	return hex.EncodeToString(hmacHash.Sum(nil))
}

func DesEncrypt(origData string) ([]byte, error) {
	key := "A123456A"
	block, err := des.NewCipher([]byte(key))
	if err != nil {
		return nil, err
	}
	origData = string(PKCS5Padding([]byte(origData), block.BlockSize()))
	// origData = ZeroPadding(origData, block.BlockSize())
	blockMode := cipher.NewCBCEncrypter(block, []byte(key))
	crypted := make([]byte, len(origData))
	// 根据CryptBlocks方法的说明，如下方式初始化crypted也可以
	// crypted := origData
	blockMode.CryptBlocks(crypted, []byte(origData))
	return crypted, nil
}

